package com.psnoted.backend.service;

import com.psnoted.backend.dto.UnifiedVerificationRequest;
import com.psnoted.backend.dto.UnifiedVerificationResponse;
import com.psnoted.backend.entity.User;
import com.psnoted.backend.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 认证服务类
 * 实现统一验证的核心业务逻辑
 * 
 * @author PSNoted Team
 * @version 1.0.0
 */
@Service
@Transactional
public class AuthService {

    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);

    @Autowired
    private UserRepository userRepository;



    /**
     * 检查用户是否存在
     * 
     * @param keyHash 密钥哈希
     * @return 是否存在
     */
    public boolean userExists(String keyHash) {
        return userRepository.existsByKeyHash(keyHash);
    }

    /**
     * 根据密钥哈希获取用户信息
     * 
     * @param keyHash 密钥哈希
     * @return 用户信息
     */
    public User getUserByKeyHash(String keyHash) {
        return userRepository.findByKeyHashAndStatus(keyHash, "active").orElse(null);
    }

    /**
     * 统一验证方法
     * 根据密钥哈希自动判断用户状态，新用户自动注册，老用户验证身份
     * 
     * @param request 统一验证请求
     * @return 统一验证响应
     */
    public UnifiedVerificationResponse verifyUnified(UnifiedVerificationRequest request) {
        logger.info("开始统一验证: keyHash={}, username={}", request.getKeyHash(), request.getUsername());
        
        try {
            LocalDateTime now = LocalDateTime.now();
            
            // 查找用户是否存在
            var userOpt = userRepository.findByKeyHashAndStatus(request.getKeyHash(), "active");
            
            if (userOpt.isPresent()) {
                // 老用户：验证身份并更新登录时间
                User user = userOpt.get();
                userRepository.updateLastLoginAt(request.getKeyHash(), now);
                
                // 构建用户信息
                UnifiedVerificationResponse.UserInfo userInfo = new UnifiedVerificationResponse.UserInfo(
                    user.getUsername(),
                    user.getKeyHash(),
                    user.getCreatedAt().toEpochSecond(ZoneOffset.UTC),
                    now.toEpochSecond(ZoneOffset.UTC)
                );
                
                logger.info("老用户验证成功: keyHash={}, username={}", request.getKeyHash(), request.getUsername());
                return new UnifiedVerificationResponse(false, user.getKeyHash(), user.getUsername(), userInfo);
            } else {
                // 新用户：自动注册
                User newUser = new User(request.getKeyHash(), request.getUsername());
                newUser.setStatus("active");
                newUser.setCreatedAt(now);
                newUser.setLastLoginAt(now);
                
                User savedUser = userRepository.save(newUser);
                
                // 构建用户信息
                UnifiedVerificationResponse.UserInfo userInfo = new UnifiedVerificationResponse.UserInfo(
                    savedUser.getUsername(),
                    savedUser.getKeyHash(),
                    savedUser.getCreatedAt().toEpochSecond(ZoneOffset.UTC),
                    savedUser.getLastLoginAt().toEpochSecond(ZoneOffset.UTC)
                );
                
                logger.info("新用户自动注册成功: keyHash={}, username={}", request.getKeyHash(), request.getUsername());
                return new UnifiedVerificationResponse(true, savedUser.getKeyHash(), savedUser.getUsername(), userInfo);
            }
        } catch (Exception e) {
            logger.error("统一验证异常: keyHash={}, username={}, error={}", 
                request.getKeyHash(), request.getUsername(), e.getMessage(), e);
            throw new RuntimeException("统一验证失败", e);
        }
    }
} 